// DataSet.cpp: implementation of the DataSet class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "DataSet.h"
#include "DBConnectionManager.h"
#include "ProductCatalogManager.h"
#include "PropertyStack.h"
#include "DBVariable.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

using namespace JointSystem;
using namespace PropertySystem;

DataSet::DataSet()
{

}

DataSet::~DataSet()
{

}

CString DataSet::GetSourceURL()
{	
	ASSERT(!this->GetDataStandard().IsEmpty());
	ProductCatalog* pCatalog = ProductCatalogManager::Instance()->
		GetProductCatalog(this->GetDataStandard());
	ASSERT(pCatalog);

	return pCatalog->DataSourceURI();
}

BOOL PropertyDataSet::InitProperty(ModelObject& object)
{
	PropertySystem::PropertyStack* pStack = object.GetPropertyStack();

	PropertyStack::Iterator *pIterator = pStack->NewFilteriterator(&m_theTables);

	for(pIterator->Begin(); !pIterator->End(); pIterator->Next())
	{
		PropertySystem::DBVariable* pVariable = static_cast<DBVariable*>(pIterator->Get());
		ASSERT(pVariable->PropertyStyle() == PropertySystem::PropertyVariable::eDB);
		
		try
		{
			*(static_cast<Variable*>(pVariable)) = m_rs->GetCollect(_variant_t(pVariable->PropertyField()));
			pVariable->SetKnown();
			
		}
		catch(_com_error e)
		{			
			ErrorAlert(e);
		}
	}
	delete pIterator;
	
	if(object.IsAllDBPropertiesKnown())
	{
		BOOL bIsNeedUpdate = TRUE;
		PropertySystem::PropertyStack::Iterator* pIt = pStack->NewIterator();
		int nCount = 0;
		while(bIsNeedUpdate)
		{
			bIsNeedUpdate = FALSE;
			for(pIt->Begin(); !pIt->End(); pIt->Next())
			{
				PropertySystem::PropertyVariable* pVar = static_cast<PropertySystem::PropertyVariable*>(pIt->Get());
				ASSERT(pVar);
				if(pVar->PropertyStyle() == PropertySystem::PropertyVariable::eNONDB && (!pVar->IsKnown() || !pVar->IsEffect()))
				{
					pVar->InitValue();
					bIsNeedUpdate = TRUE;
				}
				
			}
			nCount++;
			if(nCount >= 10)
			{
				ASSERT(FALSE);
				break;
			}
		}
		delete pIt;
	}
	return TRUE;
}

void PropertyDataSet::Close()
{
	if(m_rs != NULL && m_rs->GetState() == adStateOpen)
		m_rs->Close();

	m_rs = NULL;
}